package com.shaoshaohuo.app.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMap.OnCameraChangeListener;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.CargoListAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Cargo;
import com.shaoshaohuo.app.entity.CargoListEntity;
import com.shaoshaohuo.app.entity.CargoListEntity.CargoList;
import com.shaoshaohuo.app.entity.SearchGoods;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * 我要找货
 * @author cao
 *
 */
public class FindGoodsActivity extends BaseActivity implements OnClickListener, IXListViewListener, OnMarkerClickListener, OnInfoWindowClickListener,
                InfoWindowAdapter, OnCameraChangeListener {

    public static final int SEARCH = 50;

    private TopbarView mTopbarView;

    private XListView mCargoListview;

    private MapView mapView;

    private List<Cargo> mDataList = new ArrayList<Cargo>();
    private int size = 10;
    private String action = ListViewAction.NEW;
    private String cursor = "0";
    private String lng;
    private String lat;
    private boolean isMap = true;


    private CargoListAdapter<Cargo> mAdapter;

    private AMap aMap;
    private HashMap<Marker, Cargo> markerMap = new HashMap<>();
    private List<Cargo> dataList;

    private SearchGoods searchGoods = new SearchGoods();

    private TextView tv_search;
    private RelativeLayout rl_search;
    private TextView tv_send_ad;
    private TextView tv_end_ad;
    private TextView tv_search_detail;
    private ImageView iv_cancel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_goods);
        initView(savedInstanceState);
        setUpView();
//        requestData(true);
        changeShowState();
        initTts();
    }

    private void initView(Bundle savedInstanceState) {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
        mCargoListview = (XListView) this.findViewById(R.id.listview_cargo_list);

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
        aMap = mapView.getMap();

        tv_search = (TextView) findViewById(R.id.tv_search);
        rl_search = (RelativeLayout) findViewById(R.id.rl_search);
        tv_send_ad = (TextView) findViewById(R.id.tv_send_ad);
        tv_end_ad = (TextView) findViewById(R.id.tv_end_ad);
        tv_search_detail = (TextView) findViewById(R.id.tv_search_detail);
        iv_cancel = (ImageView) findViewById(R.id.iv_cancel);
    }

    private void setUpView() {
        mTopbarView.setCenterText("我要找货");
        mTopbarView.setLeftView(true, true);
        mTopbarView.setRightText("开启听单模式");
        mTopbarView.setRightClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mTts.isSpeaking()) {
                    mTts.stopSpeaking();
//                    pauseSpeaking();
                    playIndex = 0;
                    // showToast("听音模式已经开启")
                } else {
                    startPlayAudio("开启听单模式");
                }
            }
        });
        mCargoListview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cargo cargo = (Cargo) parent.getItemAtPosition(position);
                Intent intent = new Intent(FindGoodsActivity.this, GrabOrderActivity.class);
                intent.putExtra(ExtraName.orderid, cargo.getOrderid());
                startActivity(intent);
            }
        });

        mapView.setVisibility(View.VISIBLE);
        mCargoListview.setVisibility(View.GONE);
        setListView();
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.setOnCameraChangeListener(this);

        iv_cancel.setOnClickListener(this);
        tv_search.setOnClickListener(this);
        rl_search.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancel:
                searchGoods  = new SearchGoods();
                rl_search.setVisibility(View.GONE);
                tv_search.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_search:
            case R.id.rl_search:
                Intent intent = new Intent(this, SearchGoodsActivity.class);
                intent.putExtra(ExtraName.searchGoods, searchGoods);
                startActivityForResult(intent, SEARCH);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SEARCH) {
                searchFinish(data);
            }
        }
    }

    private void searchFinish(Intent data) {
        searchGoods = (SearchGoods) data.getSerializableExtra(ExtraName.searchGoods);
        onRefresh();
        if (TextUtils.isEmpty(searchGoods.origincityid)) {
            tv_send_ad.setText("全国");
        } else {
            tv_send_ad.setText(searchGoods.originName);
        }
        if (TextUtils.isEmpty(searchGoods.receivecityid)) {
            tv_end_ad.setText("全国");
        }else{
            tv_end_ad.setText(searchGoods.receiveName);
        }

        StringBuilder stringBuilder = new StringBuilder();
        if (searchGoods.shipptype != 0)
            stringBuilder.append(searchGoods.shippName + ",");
        if(searchGoods.ranktype!=0)
            stringBuilder.append(searchGoods.rankName + ",");
        String str = stringBuilder.toString();
        if (str.endsWith(",")) {
            str.substring(0, str.length() - 1);
        }
        tv_search_detail.setText(str);
        tv_search.setVisibility(View.GONE);
        rl_search.setVisibility(View.VISIBLE);
    }

    private void changeShowState() {
        isMap = false;
        mCargoListview.setVisibility(View.VISIBLE);
        if(mapView != null){
        	mapView.setVisibility(View.GONE);
        	((ViewGroup) getWindow().getDecorView()).removeView(mapView);
        	mapView.onDestroy();
        	mapView = null;
        }
        clearRefresh();
    }





    private void clearRefresh() {
        mDataList.clear();
        onRefresh();
    }

    private void requestData(boolean isLoading) {
        if (isLoading) {
            startLoadingDialog();
        }

        RequestService.getInstance().searchCargo(this, action,
                size + "", cursor, lng + "", lat + "", searchGoods.shipptype + "", searchGoods.ranktype + "",
                searchGoods.origincityid, searchGoods.receivecityid, isMap,
                CargoListEntity.class, new RequestListener() {

                            @Override
                            public void onSuccess(int requestCode, BaseEntity resultData) {
                                dismissLoadingDialog();
                                if (resultData.isOk()) {
                                    CargoListEntity entity = (CargoListEntity) resultData;

                                    CargoList data = entity.getData();
                                    List<Cargo> list = data.getList();
                                    mDataList.addAll(list);

                                    if ((mDataList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
                                        // mOrderListview.setPullLoadEnable(false);
                                        mCargoListview.endLoadingMore("没有更多了");
                                    }
                                    setAdapter(mDataList);

                                } else {
                                    showToast(resultData.getMsg());
                                }
                                onLoad();

                            }

                            @Override
                            public void onFailed(int requestCode, Exception error, String msg) {
                                dismissLoadingDialog();
                                showToast(R.string.please_check_network);
                                onLoad();
                            }
                        });
    }

    protected void setAdapter(List<Cargo> list) {
        this.dataList = list;
        if (isMap) {
            markerMap.clear();
            for (Cargo cargo : list) {
                LatLng ll = new LatLng(Double.parseDouble(cargo.getOriginlat()), Double.parseDouble(cargo.getOriginlng()));
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(ll);
                markerOptions.title("货源位置");
                markerOptions.snippet("测试");
                markerOptions.draggable(true);
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_cargo_weizhi));

                Marker addMarker = aMap.addMarker(markerOptions);

                markerMap.put(addMarker, cargo);
            }
        } else {
            if (mAdapter == null) {
                mAdapter = new CargoListAdapter<Cargo>(this, list, false);
                mCargoListview.setAdapter(mAdapter);
            } else {
                mAdapter.setData(list);
            }
        }

    }

    private void setListView() {
        mCargoListview.setPullLoadEnable(true);
        mCargoListview.setPullRefreshEnable(true);
        mCargoListview.setXListViewListener(this);
    }

    @Override
    public void onRefresh() {
//        if (mDataList.size() > 0) {
//            cursor = mDataList.get(0).getCursor();
//        } else {
            cursor = "0";
//        }
            mDataList.clear();
        playIndex = 0;
        action = ListViewAction.NEW;
        mCargoListview.setPullLoadEnable(true);
        requestData(false);
    }

    @Override
    public void onLoadMore() {
        if (mDataList.size() > 0) {
            cursor = mDataList.get(mDataList.size() - 1).getCursor();
        } else {
            cursor = "";
        }
        action = ListViewAction.HISTORY;
        requestData(false);
    }

    private void onLoad() {
        mCargoListview.stopRefresh();
        mCargoListview.stopLoadMore();
        // mCargoListview.setRefreshTime(StringHelper.formatDate(System.currentTimeMillis()+""));
    }

    @Override
    public View getInfoContents(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public View getInfoWindow(Marker arg0) {

        Cargo cargo = markerMap.get(arg0);
        if (cargo != null) {
            View view = View.inflate(this, R.layout.view_cargo_poi_item, null);
            TextView tv1 = (TextView) view.findViewById(R.id.textview_title);
            TextView tv2 = (TextView) view.findViewById(R.id.textview_start_end);
            TextView tv3 = (TextView) view.findViewById(R.id.textview_contact);
            TextView tv4 = (TextView) view.findViewById(R.id.textview_time);
            tv1.setText(cargo.getOriginaddress());
            tv2.setText(cargo.getOrigincityname() + "-" + cargo.getReceivecityname());
            tv3.setText("联系人:" + cargo.getShipperuserinfo().getRealname());
            tv4.setText("发货时间:" + cargo.getOrigintime());
            return view;
        }
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker arg0) {
        Cargo cargo = markerMap.get(arg0);
        if (cargo != null) {
            Intent intent = new Intent(FindGoodsActivity.this, GrabOrderActivity.class);
            intent.putExtra(ExtraName.orderid, cargo.getOrderid());
            startActivity(intent);
        }
    }

    @Override
    public boolean onMarkerClick(Marker arg0) {
        if (arg0.isInfoWindowShown()) {
            arg0.hideInfoWindow();
            return true;
        } else {
            // arg0.showInfoWindow();
        }
        return false;
    }

    @Override
    public void onCameraChange(CameraPosition arg0) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition arg0) {

    }

    // --------------听音模式-----------------

    private int playIndex = 0;

    private String getAudioText() {
        if (dataList != null && dataList.size() > playIndex) {
            Cargo cargo = dataList.get(playIndex);
            return dataList.get(playIndex).getOrigincityname() + "到" + dataList.get(playIndex).getReceivecityname() + "，发货时间为："
                            + cargo.getOrigintime() + ",期望到货时间为:" + cargo.getReceivetime();
        } else {
            return null;
        }
    }

    // 语音合成对象
    private SpeechSynthesizer mTts;
    // 默认发音人
    private String voicer = "xiaoyan";
    // 缓冲进度
    private int mPercentForBuffering = 0;
    // 播放进度
    private int mPercentForPlaying = 0;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    private Toast mToast;
    private static String TAG = FindGoodsActivity.class.getSimpleName();

    private void initTts() {
        mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
    }

    private void startPlayAudio(String text) {
        // String text = ((EditText) findViewById(R.id.tts_text)).getText().toString();
        // 设置参数
        setParam();
        int code = mTts.startSpeaking(text, mTtsListener);
        // /**
        // * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
        // * text:要合成的文本，uri:需要保存的音频全路径，listener:回调接口
        // */
        // String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
        // int code = mTts.synthesizeToUri(text, path, mTtsListener);
        if (code != ErrorCode.SUCCESS) {
            // if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
            // // 未安装则跳转到提示安装页面
            // mInstaller.install();
            // } else {
            showTip("语音合成失败,错误码: " + code);
            // }
        }
    }

    public void pauseSpeaking() {
        mTts.pauseSpeaking();
    }

    public void resumeSpeaking() {
        mTts.resumeSpeaking();
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败,错误码：" + code);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            showTip("开始播放");
        }

        @Override
        public void onSpeakPaused() {
            showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
            // 合成进度
            mPercentForBuffering = percent;
            // showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering,
            // mPercentForPlaying));
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
            // showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering,
            // mPercentForPlaying));
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                showTip("播放完成");
                String audioText = getAudioText();
                if (!TextUtils.isEmpty(audioText)) {
                    startPlayAudio(audioText);
                    playIndex++;
                }
            } else if (error != null) {
                showTip(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            // if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            // Log.d(TAG, "session id =" + sid);
            // }
        }
    };

    private void showTip(final String str) {
        // showToast(str);
    }

    /**
     * 参数设置
     * 
     * @return
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
        }
        // 设置合成语速
        mTts.setParameter(SpeechConstant.SPEED, "50");
        // 设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        // 设置合成音量
        mTts.setParameter(SpeechConstant.VOLUME, "50");
        // 设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTts.stopSpeaking();
        // 退出时释放连接
        mTts.destroy();
        if(mapView != null){
        	mapView.onDestroy();
        }

    }

    @Override
    protected void onResume() {
        // 移动数据统计分析
        FlowerCollector.onResume(this);
        FlowerCollector.onPageStart(TAG);
        if(mapView != null){
        	mapView.onResume();
        }
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        // 移动数据统计分析
        FlowerCollector.onPageEnd(TAG);
        FlowerCollector.onPause(this);
        if(mapView != null){
        	mapView.onPause();
        }
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(mapView != null){
        	mapView.onSaveInstanceState(outState);
        }
    }
}
